package com.example.utils.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReadDataListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadDataListener.class);

    Map<Integer, String> reflect = new HashMap<>();

    List<Map<String, String>> dataList = new ArrayList<>();

    boolean isFirst = true;

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
        String s = data.toString();
        LOGGER.info("解析到一条数据:{}", s);

        s = s.substring(1, s.length() - 1);
        String[] split = s.replaceAll(" ", "").split(",");


        Map<String, String> value = null;
        if (!isFirst) {
            value = new HashMap<>();
        }

        for (int i = 0; i < split.length; i++) {
            String[] dataString = split[i].split("=");
            if (isFirst) {
                reflect.put(Integer.parseInt(dataString[0]), dataString[1]);
                continue;
            }
            value.put(reflect.get(Integer.parseInt(dataString[0])), dataString[1]);
        }
        if (null != value) {
            dataList.add(value);
        }
        isFirst = false;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        LOGGER.info("所有数据解析完成！" + dataList.toString());
    }
}
